<template>
  <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑角色' : '新增角色'">
    <el-form ref="formRef" :model="roleForm" label-width="100px" :rules="rules">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="roleForm.name" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="roleForm.description" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button color="#19af7d" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, computed, watch, ref } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";

// 定义表单数据类型
type RoleForm = {
  name: string;
  description: string;
};

const props = defineProps<{
  modelValue: boolean;
  isEdit: boolean;
  roleFormData: RoleForm; // 接收父组件传递的角色数据
}>();

const emit = defineEmits(["update:modelValue", "save", "close"]);

const roleForm = reactive<RoleForm>({ ...props.roleFormData });

// 更新表单数据
watch(
  () => props.roleFormData,
  (newData) => {
    Object.assign(roleForm, newData);
  },
  { immediate: true }
);

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
});

const formRef = ref<FormInstance>();
// 表单验证规则
const rules = reactive<FormRules<RoleForm>>({
  name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
});

const handleClose = () => {
  dialogVisible.value = false;
  Object.assign(roleForm, props.roleFormData);
  emit("close");
};

const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate((valid, fields) => {
    if (valid) {
      emit("save", { ...roleForm });
      ElMessage.success(props.isEdit ? "编辑角色成功" : "新增角色成功");
      handleClose();
    } else {
      console.log("error submit!", fields);
    }
  });
};
</script>

<style lang="scss" scoped></style>
